#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<windows.h>
//宏定义
#define high 20
#define width 50

//全局变量————————————————
int canvas[high][width];
int i,j;
int moveDirection;//小蛇移动方向

//光标移动到（x,y）位置
void gotoxy(int x,int y)   
{	HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
	COORD pos;
	pos.X = x;
	pos.Y = y;
	SetConsoleCursorPosition(handle,pos);
}

void HideCursor()
{
	CONSOLE_CURSOR_INFO cursor_info = {1,0};  //表示隐藏光标
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cursor_info);
}
//数据初始化
void startup()
{
	//边框的设定
	canvas[high][width]=0;
	for(i=0;i<high;i++)
	{	
		for(j=0;j<width;j++)
		{
			canvas[i][0]=-1;
			canvas[0][j]=-1;
			canvas[i][width-1]=-1;
			canvas[high-1][j]=-1;
		}
	}
	//蛇身设定
	canvas[high/2][width/2]=1;
	for(i=0;i<=4;i++)
	{
		canvas[high/2][width/2-i]=i+1;
	}
	moveDirection=4;
}	
//小蛇移动方向
void MoveDirection()
{
	int max=0;
	int oldTail_i,oldTail_j;//记录旧的蛇尾坐标
	int oldHead_i,oldHead_j;//记录旧的蛇头位置
	
	for(i=1;i<width-1;i++)
	{
		for(j=1;j<high-1;j++)
		{
			//对所有大于0的数加1
			if(canvas[i][j]>=0)
				canvas[i][j]++;
			//求最大值max
			if(max<canvas[i][j])
			{
				max=canvas[i][j];
				oldTail_i=i;
				oldTail_j=j;
			}	
			//记录蛇头的旧位置
			if(canvas[i][j]==2)
			{
				oldHead_i=i;
				oldHead_j=j;
			}
		   
		}
	}
	canvas[oldTail_i][oldTail_j]=0;//最大值所在元素变为零 
	
	int newHead_i,newHead_j;

	//蛇的移动
	if(moveDirection==1)//向上
	{
		canvas[oldHead_i-1][oldHead_j]=1;
		newHead_i=oldHead_i-1;
		newHead_j=oldHead_j;
	}
	if(moveDirection==2)//向下
	{
		canvas[oldHead_i+1][oldHead_j]=1;
		newHead_i=oldHead_i+1;
		newHead_j=oldHead_j;
	}
	if(moveDirection==3)//向左
	{
		canvas[oldHead_i][oldHead_j-1]=1;
		newHead_i=oldHead_i;
		newHead_j=oldHead_j-1;
	}
	if(moveDirection==4)//向右
	{
		canvas[oldHead_i][oldHead_j+1]=1;
		newHead_i=oldHead_i;
		newHead_j=oldHead_j+1;
	}
	//pantua判断蛇头是否撞墙
	if(canvas[newHead_i][newHead_j]>0 || canvas[newHead_i][newHead_j]==-1)
	{
		printf("Game over!!!");
		exit(0);
	}
	else
	{
		canvas[newHead_i][newHead_j]=1;
	}
}

//页面显示
void show()
{
	gotoxy(0,0);
	for(i=0;i<high;i++)\
	{
		for(j=0;j<width;j++)
		{
			if(canvas[i][j]==-1)
				printf("o");//输出边框
			else if(canvas[i][j]==1)
				printf("@");
			else if(canvas[i][j]>1)
				printf("#");
			else
				printf(" ");
		}
		printf("\n");
	}
	HideCursor();
}
//与输入无关的
void updateWithoutInput()
{
	MoveDirection();

	
}
  
//与输入有关的
void  updateWithInput()
{
	char input;
	if(kbhit())
	{
		input=getch();
		if(input=='A')
			moveDirection=3;
		if(input=='D')
			moveDirection=3;
		if(input=='W')
			moveDirection=3;
		if(input=='S')
			moveDirection=3;
	}
}
//主函数
int main()
{
	startup();
	while (1)
	{
		show();
		updateWithInput();
		updateWithoutInput();
	}
	return 0;
}